/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.group.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.group.entity.BizGroup;
import vip.xiaonuo.biz.modular.group.entity.BizGroupUser;
import vip.xiaonuo.biz.modular.group.mapper.BizGroupMapper;
import vip.xiaonuo.biz.modular.group.mapper.BizGroupUserMapper;
import vip.xiaonuo.biz.modular.group.param.*;
import vip.xiaonuo.biz.modular.group.service.BizGroupUserService;
import vip.xiaonuo.biz.modular.org.entity.BizOrg;
import vip.xiaonuo.biz.modular.org.mapper.BizOrgMapper;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.mapper.BizUserMapper;
import vip.xiaonuo.common.enums.CommonExceptionEnum;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.sys.api.SysOrgApi;
import vip.xiaonuo.sys.api.SysUserApi;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 社团申请表Service接口实现类
 *
 * @author 薛守立
 * @date  2024/07/01 14:37
 **/
@Service
public class BizGroupUserServiceImpl extends ServiceImpl<BizGroupUserMapper, BizGroupUser> implements BizGroupUserService {

    @Autowired
    BizGroupMapper bizGroupMapper;

    @Autowired
    BizOrgMapper bizOrgMapper;

    @Resource
    SysUserApi sysUserApi;

    @Resource
    SysOrgApi sysOrgApi;

    @Autowired
    BizUserMapper bizUserMapper;


    @Override
    public Page<BizGroupUser> page(BizGroupUserPageParam bizUserGroupPageParam) {
        QueryWrapper<BizGroupUser> queryWrapper = new QueryWrapper<BizGroupUser>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(bizUserGroupPageParam.getSortField(), bizUserGroupPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizUserGroupPageParam.getSortOrder());
            queryWrapper.ne("JOIN_STATUS", 1).orderBy(true, bizUserGroupPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizUserGroupPageParam.getSortField()));
        } else {
            queryWrapper.lambda().ne(BizGroupUser::getJoinStatus, 3).orderByAsc(BizGroupUser::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizGroupUserAddParam bizUserGroupAddParam) {
        BizGroupUser bizUserGroup = BeanUtil.toBean(bizUserGroupAddParam, BizGroupUser.class);
        BizGroup bizGroup = bizGroupMapper.selectById(bizUserGroup.getGroupId());
        bizUserGroup.setCreateId(bizGroup.getManagerId());
        this.save(bizUserGroup);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizGroupUserEditParam bizUserGroupEditParam) {
        BizGroupUser bizUserGroup = this.queryEntity(bizUserGroupEditParam.getId());
        BeanUtil.copyProperties(bizUserGroupEditParam, bizUserGroup);
        this.updateById(bizUserGroup);
    }

    @Override
    public BizGroupUser queryEntity(String id) {
        BizGroupUser bizUserGroup = this.getById(id);
        if(ObjectUtil.isEmpty(bizUserGroup)) {
            throw new CommonException("社团申请表不存在，id值为：{}", id);
        }
        return bizUserGroup;
    }

    @Override
    public void joinGroup(BizUser user, BizGroup group) {
        // 查询是否有关联信息
        QueryWrapper<BizGroupUser> queryWrapper = new QueryWrapper<BizGroupUser>().checkSqlInjection();
        queryWrapper.lambda().eq(BizGroupUser::getGroupId, group.getId()).eq(BizGroupUser::getUserId, user.getId());
        BizGroupUser bizUserGroup = this.getOne(queryWrapper);
        if(bizUserGroup != null) throw new CommonException(CommonExceptionEnum.ERROR_JOIN_GROUP);
        BizGroupUserAddParam bizUserGroupAddParam = new BizGroupUserAddParam();
        bizUserGroupAddParam.setGroupId(group.getId());
        bizUserGroupAddParam.setUserId(user.getId());
        bizUserGroupAddParam.setApplyId(group.getManagerId());
        bizUserGroupAddParam.setApplyName(group.getManagerName());
        bizUserGroupAddParam.setGroupName(group.getGroupName());
        bizUserGroupAddParam.setUserName(user.getName());
        this.add(bizUserGroupAddParam);
    }

    @Override
    public void applyRequest(String id, String method) {
        BizGroupUser bizUserGroup = this.queryEntity(id);
        if(bizUserGroup == null) throw new CommonException(CommonExceptionEnum.ERROR415);
        // 查询请求实体类
        BizGroupUserEditParam bizUserGroupEditParam = new BizGroupUserEditParam();
        BeanUtils.copyProperties(bizUserGroup, bizUserGroupEditParam);
        bizUserGroupEditParam.setJoinStatus(Integer.parseInt(method));
        this.edit(bizUserGroupEditParam);
    }

    @Override
    public List<BizGroupUser> getGroupList(String userId) {
        // 查询是否有关联信息
        QueryWrapper<BizGroupUser> queryWrapper = new QueryWrapper<BizGroupUser>().checkSqlInjection();
        queryWrapper.lambda().eq(BizGroupUser::getUserId, userId).eq( BizGroupUser::getJoinStatus, 1).or().eq(BizGroupUser::getCreateId, userId);
        List<BizGroupUser> bizGroupList = this.list(queryWrapper);
        return bizGroupList;
    }

    @Override
    public List<BizGroupUserVoParam> getUserList(String groupId) {
        LambdaQueryWrapper<BizGroupUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizGroupUser::getGroupId, groupId);
        queryWrapper.eq(BizGroupUser::getJoinStatus,1);
        List<BizGroupUser> bizGroupList = this.list(queryWrapper);
        List<BizGroupUserVoParam> res = new ArrayList<>();
        bizGroupList.forEach(item->{
            BizGroupUserVoParam bizGroupUserVoParam = new BizGroupUserVoParam();
            BeanUtils.copyProperties(item, bizGroupUserVoParam);
            Map<String,String> useMap = sysUserApi.getUserPhone(item.getUserId());
            bizGroupUserVoParam.setUserPhone(useMap.get("userPhone"));
            bizGroupUserVoParam.setOrgName(useMap.get("orgName"));
            res.add(bizGroupUserVoParam);
        });
        return res;
    }

    @Override
    public Page<BizGroupUser> myGroup(BizGroupUserPageParam bizGroupUserPageParam) {
        QueryWrapper<BizGroupUser> queryWrapper = new QueryWrapper<BizGroupUser>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(bizGroupUserPageParam.getSortField(), bizGroupUserPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizGroupUserPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizGroupUserPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizGroupUserPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizGroupUser::getId);
        }
        String userId = StpUtil.getLoginIdAsString();
        queryWrapper.lambda().eq(BizGroupUser::getApplyId, userId);
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public Page<BizGroupUser> getMyApply(BizGroupUserPageParam bizGroupUserPageParam) {
        QueryWrapper<BizGroupUser> queryWrapper = new QueryWrapper<BizGroupUser>().checkSqlInjection();
        if(ObjectUtil.isAllNotEmpty(bizGroupUserPageParam.getSortField(), bizGroupUserPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizGroupUserPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizGroupUserPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizGroupUserPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizGroupUser::getId);
        }
        String userId = StpUtil.getLoginIdAsString();
        queryWrapper.lambda().eq(BizGroupUser::getUserId, userId);
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public void delete(List<BizGroupUserIdParam> bizGroupUserIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizGroupUserIdParamList, BizGroupUserIdParam::getId));
    }

    @Override
    public List<String> getUserWechatId(List<String> groupId) {
        List<String> userWechatList = new ArrayList<>();
        groupId.forEach(item->{
            LambdaQueryWrapper<BizGroupUser> lqw = new LambdaQueryWrapper();
            lqw.eq(BizGroupUser::getGroupId, item);
            List<BizGroupUser> bizGroupUser = this.list(lqw);
            if(bizGroupUser==null) throw new CommonException("社团组织内无加入的用户");
            bizGroupUser.forEach(i->{
                BizUser bizUser = bizUserMapper.selectById(i.getUserId());
                if(bizUser.getClientId()!=null) userWechatList.add(bizUser.getClientId());
            });
        });
        return userWechatList;
    }

    @Override
    public List<String> getOrgWechatId(List<String> orgId) {
        List<String> wechatList = new ArrayList<>();
        orgId.forEach(item->{
            BizOrg bizOrg = bizOrgMapper.selectById(item);
            wechatList.add(bizOrg.getWechatId());
        });
        return wechatList;
    }
}
